package org.brownflat.lighthouse.monitor;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.action.Action;
import org.brownflat.lighthouse.ci.Monitorable;
import org.brownflat.lighthouse.device.Device;

public class AnyBrokenBuildTask implements LighthouseTask {

	private Monitorable monitorable;
	private Action whenBroken;
	private Action whenNotBroken;
	private Action whenResetNeeded;
	private boolean broken = false;
	private String name = null;
	private Device device;
	private static final Logger LOG = Logger.getLogger(AnyBrokenBuildTask.class);

	public AnyBrokenBuildTask(String name, Monitorable monitorable, Device device, Action reset, Action broken, Action notBroken) {
		this.monitorable = monitorable;
		this.device = device;
		this.whenBroken = broken;
		this.whenNotBroken = notBroken;
		this.whenResetNeeded = reset;
		this.name = name;
	}

	@Override
	public void run() {
		LOG.debug("Checking for any broken build");
		if(monitorable.hasAnyBrokenBuilds()) {
			if(!broken) {
                execute(whenResetNeeded);
			}

			broken = true;
            execute(whenBroken);
			LOG.error("BROKEN BUILD DETECTED.");
		} else {
			if(broken) {
				LOG.error("BROKEN BUILD FIXED.");
                execute(whenResetNeeded);
			}
			LOG.info("BUILDS OK.");
			broken = false;
            execute(whenNotBroken);
		}
	}

    @SuppressWarnings("unchecked")
    private void execute(Action action) {
        LOG.debug("Action executing: " + action.getActionDescription());
        device.execute(action);

        //sometimes the device needs a couple of seconds to absorb the command
        //before the next one, so pause here.
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException e) {
            LOG.error(e);
        }
    }

    public Monitorable getMonitorable() {
        return monitorable;
    }

    @Override
	public String getName() {
		return name;
	}
}
